<script setup lang="ts">
import _axios from '../../utils/myAxios.js';
import { ref, reactive, onMounted } from 'vue'
import { useSessionStorage } from '@vueuse/core'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// ------------------------------------------登录页左边二维码-----------------------------------------------
let code = ref("http://47.92.174.180:8080/profile/2025/04/08/friend.png")
let codeName = ref("微信") //二维码
const activeName = ref('login')
const router = useRouter()
const changeWeiXinCode = () => { //切换微信好友码
    code.value = "http://47.92.174.180:8080/profile/2025/04/08/friend.png"
    // code.value = "src/assets/image/friend.png"
    codeName.value = "微信"
}
const changeQQCode = () => { //切换qq好友码
    code.value = "http://47.92.174.180:8080/profile/2025/04/08/QQ.jpg"
    // code.value = "src/assets/image/QQ.png"
    codeName.value = "QQ"
}
// ------------------------------------------ 登录 -----------------------------------------------
let loginForm = reactive({ //登录表单数据
    username: "",
    password: "",
    // remember: false,
    captcha: ""
})
let captchaRef = ref({
    img: '',
    key: ''
})
async function captcha() { //登录请求后端验证码图片并转化为临时地址
    let resp = await _axios.get("/api/auth/getCaptcha")
    captchaRef.value = resp.data.data
}
const loginRule = reactive({ //登录表单规则
    username: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type:"email", message: '请输入合法的电子邮件地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '长度为4个字符', trigger: 'blur' }
    ]
})
let loginRef = ref()
async function login() { //登录验证请求
    loginRef.value.validate(async (valid: boolean) => {
        if (valid) {
            let captcha = await _axios.get("/api/auth/verifyCaptcha/" + loginForm.captcha + "/" + captchaRef.value.key)
            if (captcha.data.code == 609) {
                ElMessage({
                    showClose: true,
                    message: captcha.data.message,
                    type: 'error',
                    appendTo: "#app",
                })
                location.reload();
            } else {
                if (captcha.data.code === 200) {
                    let resp = await _axios.post("/api/auth/login", {
                        username: loginForm.username,
                        password: loginForm.password
                    },
                        {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            }
                        })
                    if (resp.data.code === 200) {
                        let token = JSON.stringify({ Authorization: resp.data.data.token, expireTime: resp.data.data.expireTime })
                        localStorage.setItem("Authorization", token)
                        router.push("/home")
                    }else {
                        ElMessage({
                            showClose: true,
                            message: resp.data.message,
                            type: 'error',
                            appendTo: "#app",
                        })
                        location.reload();
                    }
                } else {
                    ElMessage({
                        showClose: true,
                        message: '验证码错误',
                        type: 'error',
                        appendTo: "#app",
                    })
                }
            }

        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}


onMounted(() => {
    captcha()
})

// ------------------------------------------忘记密码-----------------------------------------------

let active = ref(0)

//forgotRule中的自定义校验
const forgotPassword_repeat = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== forgotForm.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const forgotRule = reactive({
    username: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type:"email", message: '请输入合法的电子邮件地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
    ],
    password_repeat: [
        { validator: forgotPassword_repeat, trigger: 'blur' }
    ],
    checkCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6, max: 6, message: '长度为6个字符', trigger: 'blur' }
    ]
})
let forgotRef = ref()
let forgotForm = reactive({ //忘记密码表单数据
    username: "",
    checkCode: "",
    password: "",
    password_repeat: ""
})
let forgotCount = ref(60)
let forgotFirstDate = ref(0)


async function getForgotCode() {
    let resp = await _axios.get("/api/auth/forgotCode?username=" + forgotForm.username)
    if (resp.data.code === 200) {
        ElMessage({
            showClose: true,
            message: "邮件发送成功，请注意接收",
            type: 'success',
            appendTo: "#app"
        })
        let lastDate = new Date().getTime()
        if (lastDate - forgotFirstDate.value > 60000) {
            forgotFirstDate.value = new Date().getTime()
            let date = setInterval(() => {
                forgotCount.value--
                if (forgotCount.value === 0) {
                    forgotCount.value = 60
                    sessionStorage.removeItem("forgotFirstDate")
                    clearInterval(date)
                }
            }, 1000);
        } else {
            ElMessage({
                showClose: true,
                message: "请勿频繁请求验证码",
                type: 'warning',
                appendTo: "#app",
            })
        }
    } else {
        ElMessage({
            showClose: true,
            message: resp.data.message,
            type: 'error',
            appendTo: "#app"
        })
    }
}

async function forgot() {
    forgotRef.value.validate(async (valid: boolean) => {
        if (valid) {
            let resp = await _axios.post("/api/auth/forgot", {
                username: forgotForm.username,
                checkCode: forgotForm.checkCode
            })
            if (resp.data.code === 200) {
                active.value++
            } else {
                ElMessage({
                    showClose: true,
                    message: resp.data.message,
                    type: 'error',
                    appendTo: "#app"
                })
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}

//第二步修改密码
async function changePassword() {
    forgotRef.value.validate(async (valid: boolean) => {
        if (valid) {
            let resp = await _axios.post("/api/auth/changePassword", {
                username: forgotForm.username,
                password: forgotForm.password
            })
            if (resp.data.code === 200) {
                active.value++
            } else {
                ElMessage({
                    showClose: true,
                    message: resp.data.message,
                    type: 'error',
                    appendTo: "#app"
                })
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}
function reload() {
    location.reload()
}
// ------------------------------------------ 注册 -----------------------------------------------
let registerForm = reactive({ //注册表单数据
    nickname: "",
    username: "",
    password: "",
    checkCode: ""
})
const registerRule = reactive({
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 1, max: 14, message: '长度在 1 到 14 个字符', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type:"email", message: '请输入合法的电子邮件地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
    ],
    checkCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6, max: 6, message: '长度为6个字符', trigger: 'blur' }
    ]
})

let registerRef = ref()
let emilCode = ref("请求验证码") //注册二维码按钮信息
let count = ref(60)
let firstDate = ref(0)
useSessionStorage('firstDate', firstDate) //在seesion中存储首次请求时间
useSessionStorage('forgotFirstDate', forgotFirstDate)
async function getEmilCode() {
    let resp = await _axios.get("/api/auth/sendEmail?username=" + registerForm.username)
    if (resp.data.code === 200) {
        ElMessage({
            showClose: true,
            message: "邮件发送成功，请注意接收",
            type: 'success',
            appendTo: "#app"
        })
        let lastDate = new Date().getTime()
        if (lastDate - firstDate.value > 60000) {
            firstDate.value = new Date().getTime()
            let date = setInterval(() => {
                count.value--
                if (count.value === 0) {
                    count.value = 60
                    sessionStorage.removeItem("firstDate")
                    clearInterval(date)
                }
            }, 1000);
        } else {
            ElMessage({
                showClose: true,
                message: "请勿频繁请求验证码",
                type: 'warning',
                appendTo: "#app",
            })
        }
    } else {
        ElMessage({
            showClose: true,
            message: resp.data.message,
            type: 'error',
            appendTo: "#app"
        })
    }
}
async function register() {
    registerRef.value.validate(async (valid: boolean) => {
        if (valid) {
            let resp = await _axios.post("/api/auth/register", registerForm)
            if (resp.data.code === 200) {
                ElMessage({
                    showClose: true,
                    message: "注册成功",
                    type: 'success',
                    appendTo: "#app"
                })
                location.reload();
            } else {
                ElMessage({
                    showClose: true,
                    message: resp.data.message,
                    type: 'error',
                    appendTo: "#app"
                })
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}
</script>

<template>
    <div class="login">
        <div class="login-image">
            <img style="width: 220px;" src="http://47.92.174.180:8080/profile/2025/04/08/loginLogo.png" alt="">
        </div>
        <div class="login-item">
            <div class="login-item-left">
                <p class="login-item-left-title">扫码加好友</p>
                <div class="login-item-left-img">
                    <img :src="code" alt="二维码">
                </div>
                <p class="login-item-left-message">{{ codeName }}</p>
                <el-button round @click="changeWeiXinCode">微信扫码</el-button>
                <el-button round @click="changeQQCode">QQ扫码</el-button>
            </div>
            <div class="login-item-right">
                <el-tabs v-model="activeName" class="demo-tabs">
                    <el-tab-pane class="login-item-right-login" label="账号登录" name="login">
                        <el-form :model="loginForm" :rules="loginRule" ref="loginRef">
                            <el-form-item prop="username">
                                <el-input class="login-item-right-input" maxlength="20" v-model="loginForm.username"
                                    placeholder="请输入邮箱" @keyup.enter="login" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpMessage />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input class="login-item-right-input" maxlength="30" v-model="loginForm.password"
                                    type="password" placeholder="请输入密码" show-password @key.enter="login" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpLock />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="captcha">
                                <div class="chickCode">
                                    <el-input class="login-item-right-code" v-model="loginForm.captcha"
                                        placeholder="请输入验证码" @keyup.enter="login" clearable>
                                        <template #prefix>
                                            <el-icon>
                                                <iEpPromotion />
                                            </el-icon>
                                        </template>>
                                    </el-input>
                                    <img :src="captchaRef.img" alt="验证码" @click="captcha">
                                </div>
                            </el-form-item>
                        </el-form>
                        <el-button type="primary" @click="login">登录</el-button>
                    </el-tab-pane>
                    <el-tab-pane class="login-item-right-register" label="忘记密码" name="forgot">
                        <el-steps style="max-width: 600px;margin: 10px 0;" :space="200" :active="active"
                            finish-status="success" align-center>
                            <el-step title="发送验证码" />
                            <el-step title="重置密码" />
                        </el-steps>
                        <el-form :model="forgotForm" :rules="forgotRule" ref="forgotRef" v-if="active === 0">
                            <el-form-item prop="username">
                                <el-input class="login-item-right-input" v-model="forgotForm.username"
                                    placeholder="请输入邮箱" @keyup.enter="forgot" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpMessage />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="checkCode">
                                <div class="checkCode">
                                    <el-input class="login-item-right-code" v-model="forgotForm.checkCode"
                                        placeholder="请输入验证码" @keyup.enter="forgot" clearable>
                                        <template #prefix>
                                            <el-icon>
                                                <iEpPromotion />
                                            </el-icon>
                                        </template>>
                                    </el-input>
                                    <el-button v-if="forgotCount === 60" @click="getForgotCode">{{ emilCode
                                        }}</el-button>
                                    <el-button disabled v-else id="emilCode">{{ forgotCount }}后获取</el-button>
                                </div>
                            </el-form-item>
                            <el-button type="primary" @click="forgot">开始重置密码</el-button>
                        </el-form>
                        <el-form :model="forgotForm" :rules="forgotRule" ref="forgotRef" v-if="active === 1">
                            <el-form-item prop="password">
                                <el-input class="login-item-right-input" v-model="forgotForm.password" type="password"
                                    placeholder="请输入密码" show-password @keyup.enter="changePassword" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpLock />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="password_repeat">
                                <el-input class="login-item-right-input" v-model="forgotForm.password_repeat"
                                    type="password" placeholder="请再次输入密码" show-password @keyup.enter="changePassword" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpLock />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-button type="primary" @click="changePassword">立即重置密码</el-button>
                        </el-form>
                        <span v-if="active === 2" style="text-align: center;color: red;">
                            <el-row>
                                <el-col>
                                    <el-result icon="success" title="恭喜您,密码重置成功" sub-title="请妥善保管您的密码，不要再忘了哦૮(˶ᵔ ᵕ ᵔ˶)ა"
                                        style="padding-top: 0;">
                                        <template #extra>
                                            <el-button type="primary" @click="reload">前往登录</el-button>
                                        </template>
                                    </el-result>
                                </el-col>
                            </el-row>
                        </span>
                    </el-tab-pane>
                    <el-tab-pane class="login-item-right-register" label="账号注册" name="register">
                        <el-form :model="registerForm" :rules="registerRule" ref="registerRef">
                            <el-form-item prop="nickname">
                                <el-input class="login-item-right-input" v-model="registerForm.nickname"
                                    placeholder="请输入昵称" @keyup.enter="register" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpUser />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="username">
                                <el-input class="login-item-right-input" v-model="registerForm.username"
                                    placeholder="请输入邮箱" @keyup.enter="register" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpMessage />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="checkCode">
                                <div class="checkCode">
                                    <el-input class="login-item-right-code" v-model="registerForm.checkCode"
                                        placeholder="请输入验证码" @keyup.enter="register" clearable>
                                        <template #prefix>
                                            <el-icon>
                                                <iEpPromotion />
                                            </el-icon>
                                        </template>>
                                    </el-input>
                                    <el-button v-if="count === 60" @click="getEmilCode">{{ emilCode }}</el-button>
                                    <el-button disabled v-else id="emilCode">{{ count }}后获取</el-button>
                                </div>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input class="login-item-right-input" v-model="registerForm.password" type="password"
                                    placeholder="请输入密码" show-password @keyup.enter="register" clearable>
                                    <template #prefix>
                                        <el-icon>
                                            <iEpLock />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-form>
                        <el-button type="primary" @click="register">注册</el-button>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<style scoped></style>
